package com.xjk.stream;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author 许嘉凯
 */
public class StreamUtil {

  public static byte[] streamToByteArray(InputStream inputStream) throws IOException{
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] bufferBytes = new byte[2024];
    int len = 0;
    while ((len=inputStream.read(bufferBytes))!=-1){
      byteArrayOutputStream.write(bufferBytes,0,len);
    }
    byte[] bytes = byteArrayOutputStream.toByteArray();
    byteArrayOutputStream.close();
    return bytes;
  }

  public static String streamToString(InputStream inputStream) throws IOException{
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuffer stringBuffer = new StringBuffer();
    StringBuilder stringBuilder = new StringBuilder();
    String ret;
    while ((ret=reader.readLine())!=null){
      stringBuffer.append(ret).append("\n");
    }
    return String.valueOf(stringBuilder.append(stringBuffer));
  }

}
